﻿Imports System.Text.RegularExpressions
Imports System.Xml
Imports System.Text


Public Class pmSettings
  

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub


    Private Sub pmSettings_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If ConfigurationHelper.DistripostInfoFicheLocation IsNot Nothing Then
                txtLocatieInfofiche.Text = ConfigurationHelper.DistripostInfoFicheLocation
            End If
            If ConfigurationHelper.Email1 IsNot Nothing Then
                txtEmail1.Text = ConfigurationHelper.Email1
            End If
            If ConfigurationHelper.Email2 IsNot Nothing Then
                txtEmail2.Text = ConfigurationHelper.Email2
            End If
            If ConfigurationHelper.Email3 IsNot Nothing Then
                txtEmail3.Text = ConfigurationHelper.Email3
            End If

            checkStatusOntvangenBerichten()
            checkStatusVerzondenBerichten()
            checkStatusZoekmappen()


        Catch ex As System.Exception
            ExceptionHandler.ShowAndLog("Fout bij laden van instellingen", ex)
        End Try

    End Sub

    Private Sub btnOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            DialogResult = Windows.Forms.DialogResult.None

            If txtLocatieInfofiche.Text.Length = 0 Then
                MessageBox.Show("Gelieve de locatie op te geven van de Distripost Infofiche.")
                Exit Sub
            ElseIf Not txtLocatieInfofiche.Text.StartsWith("http://") And Not txtLocatieInfofiche.Text.StartsWith("https://") Then
                MessageBox.Show("De locatie van de Distripost Infofiche moet een internetadres zijn, gelieve opnieuw in te voeren.")
                Exit Sub
            End If


            'validering emailadressen
            If Not validEmails() Then
                Exit Sub
            End If

            DialogResult = Windows.Forms.DialogResult.OK

            'locatie infofiche opslaan
            ConfigurationHelper.SetKeyvalue("distripostinfofichelocation", txtLocatieInfofiche.Text)
            'e-mailadressen opslaan
            ConfigurationHelper.SetKeyvalue("email1", txtEmail1.Text)
            ConfigurationHelper.SetKeyvalue("email2", txtEmail2.Text)
            ConfigurationHelper.SetKeyvalue("email3", txtEmail3.Text)
            ' InitViews()
        Catch ex As System.Exception
            ExceptionHandler.ShowAndLog(ex.Message, ex)
        End Try
    End Sub

    Private Function validEmails() As Boolean
        If txtEmail1.Text.Length = 0 And txtEmail2.Text.Length = 0 And txtEmail3.Text.Length = 0 Then
            MessageBox.Show("Gelieve ten minste 1 e-mailadres op te geven.")
            Return False
        End If
        If txtEmail1.Text.Length > 0 AndAlso Not validEmailAddress(txtEmail1.Text) Then
            MessageBox.Show("E-mailadress 1 is geen geldig e-mailadres")
            Return False
        End If
        If txtEmail2.Text.Length > 0 AndAlso Not validEmailAddress(txtEmail2.Text) Then
            MessageBox.Show("E-mailadress 2 is geen geldig e-mailadres")
            Return False
        End If
        If txtEmail3.Text.Length > 0 AndAlso Not validEmailAddress(txtEmail3.Text) Then
            MessageBox.Show("E-mailadress 3 is geen geldig e-mailadres")
            Return False
        End If
        Return True
    End Function

    Private Function emailsSet() As Boolean
        If ConfigurationHelper.Email1 IsNot Nothing OrElse ConfigurationHelper.Email2 IsNot Nothing OrElse ConfigurationHelper.Email3 IsNot Nothing Then
            Return True
        End If
        Return False
    End Function
    Function validEmailAddress(ByVal emailAddress As String) As Boolean
        Dim EmailAddressValid As Boolean

        Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
        Dim emailAddressMatch As Match = Regex.Match(emailAddress, pattern)
        If emailAddressMatch.Success Then
            EmailAddressValid = True
        Else
            EmailAddressValid = False
        End If

        Return EmailAddressValid

    End Function

    'Private Sub InitViews()
    '    InitOntvangenBerichten()
    '    InitVerzondenBerichten()
    'End Sub

    Private Sub InitOntvangenBerichten()
        Dim vws As Outlook.Views = SharedFunctions.GetInboxFolder(Globals.ThisAddIn.Application).Views

        Dim obView As Outlook.View = Nothing


        Dim xmlDoc As New Xml.XmlDocument
        Dim viewNode As Xml.XmlNode
        Dim filterNode As XmlElement


        obView = vws("Ontvangen berichten")


        'view Ontvangen berichten eventueel aanmaken + aanpassen
        If obView IsNot Nothing Then
            obView.Delete()
        End If
        obView = vws.Add("Ontvangen berichten", Outlook.OlViewType.olTableView, Outlook.OlViewSaveOption.olViewSaveOptionAllFoldersOfType)

        xmlDoc.LoadXml(obView.XML)
        viewNode = xmlDoc.SelectSingleNode("view")

        'create new filternode
        filterNode = xmlDoc.CreateElement("filter")
        filterNode.InnerText = filterOntvangenBerichten()
        viewNode.AppendChild(filterNode)
        'filterNode.AppendChild(xmlDoc.CreateTextNode(filterOntvangenBerichten))

        'set changed xml to view and save
        obView.XML = xmlDoc.InnerXml
        obView.Save()
    End Sub
    Private Sub InitVerzondenBerichten()
        Dim vvws As Outlook.Views = SharedFunctions.GetInboxFolder(Globals.ThisAddIn.Application).Views

        Dim vvbView As Outlook.View = Nothing

        Dim vxmlDoc As New Xml.XmlDocument
        Dim vviewNode As Xml.XmlNode
        Dim vfilterNode As XmlElement


        vvbView = vvws("Verzonden berichten")

        'view Verzonden berichten eventueel aanmaken + aanpassen
        If vvbView IsNot Nothing Then
            vvbView.Delete()

        End If
        vvbView = vvws.Add("Verzonden berichten", Outlook.OlViewType.olTableView, Outlook.OlViewSaveOption.olViewSaveOptionAllFoldersOfType)

        vxmlDoc.LoadXml(vvbView.XML)
        vviewNode = vxmlDoc.SelectSingleNode("view")

        'create new filternode
        vfilterNode = vxmlDoc.CreateElement("filter")
        vfilterNode.InnerText = filterVerzondenBerichten()
        vviewNode.AppendChild(vfilterNode)

        'set changed xml to view and save
        vvbView.XML = vxmlDoc.InnerXml
        vvbView.Save()
    End Sub

    Private Function filterOntvangenBerichten() As String
        Dim filter As New StringBuilder

        Dim email1 As String = ConfigurationHelper.Email1
        Dim email2 As String = ConfigurationHelper.Email2
        Dim email3 As String = ConfigurationHelper.Email3


        If email1.Length > 0 Then
            buildFilter(filter, filterOntvanger(email1))
        End If
        If email2.Length > 0 Then
            buildFilter(filter, filterOntvanger(email2))
        End If

        If email3.Length > 0 Then
            buildFilter(filter, filterOntvanger(email3))
        End If

        If Globals.ThisAddIn.Application.GetNamespace("mapi").CurrentUser.Name.Length > 0 Then
            buildFilter(filter, filterVerzender(Globals.ThisAddIn.Application.GetNamespace("mapi").CurrentUser.Name))
        End If
        '("urn:schemas:httpmail:displayto" LIKE '%promarket@skynet.be%' OR "urn:schemas:httpmail:displaycc" LIKE '%promarket@skynet.be%')
        'Dim test As String = "((""urn:schemas:httpmail:displayto"" LIKE '%info@promarket.be%' OR ""urn:schemas:httpmail:displaycc"" LIKE '%info@promarket.be%') " & _
        '                    "OR (""urn:schemas:httpmail:displayto"" LIKE '%promarket@skynet.be%' OR ""urn:schemas:httpmail:displaycc"" LIKE '%promarket@skynet.be%'))"
        Return filter.ToString
    End Function

    Private Function filterOntvanger(ByVal emailadres As String) As String

        Return """urn:schemas:httpmail:displayto"" LIKE '%" & emailadres & "%'"
        'Return "(""urn:schemas:httpmail:displayto"" LIKE '%" & emailadres & "%' OR ""urn:schemas:httpmail:displaycc"" LIKE '%" & emailadres & "%')"
    End Function
    Private Function filterVerzender(ByVal emailadres As String) As String
        '"((""urn:schemas:httpmail:fromname"" LIKE '%info@promarket.be%' OR ""http://schemas.microsoft.com/mapi/proptag/0x0065001f"" LIKE '%info@promarket.be%') OR (""urn:schemas:httpmail:fromname"" LIKE '%promarket@skynet.be%' OR ""http://schemas.microsoft.com/mapi/proptag/0x0065001f"" LIKE '%promarket@skynet.be%'))"

        Return """urn:schemas:httpmail:fromname"" LIKE '%" & emailadres & "%'"
        ' Return "((""urn:schemas:httpmail:fromname"" LIKE '%" & emailadres & "%' OR ""http://schemas.microsoft.com/mapi/proptag/0x0065001f"" LIKE '%" & emailadres & "%') OR (""urn:schemas:httpmail:fromname"" LIKE '%" & emailadres & "%' OR ""http://schemas.microsoft.com/mapi/proptag/0x0065001f"" LIKE '%" & emailadres & "%'))"

        '"urn:schemas:httpmail:fromname" LIKE '%promarket@skynet.be%'
    End Function


    Private Function filterVerzondenBerichten() As String
        Dim filter As New StringBuilder

        Dim email1 As String = ConfigurationHelper.Email1
        Dim email2 As String = ConfigurationHelper.Email2
        Dim email3 As String = ConfigurationHelper.Email3


        If email1.Length > 0 Then
            buildFilter(filter, filterVerzender(email1))
        End If
        If email2.Length > 0 Then
            buildFilter(filter, filterVerzender(email2))
        End If

        If email3.Length > 0 Then
            buildFilter(filter, filterVerzender(email3))
        End If

        If Globals.ThisAddIn.Application.GetNamespace("mapi").CurrentUser.Name.Length > 0 Then
            buildFilter(filter, filterVerzender(Globals.ThisAddIn.Application.GetNamespace("mapi").CurrentUser.Name))
        End If

        Return filter.ToString
    End Function


    Private Sub buildFilter(ByVal filter As StringBuilder, ByVal filterToAdd As String)
        If filter.Length = 0 Then
            filter.Append(filterToAdd)
        Else
            filter.Append(" OR " & filterToAdd)
        End If
    End Sub


    Private Sub btnOntvangenBerichten_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOntvangenBerichten.Click
        If emailsSet() Then
            InitOntvangenBerichten()
            checkStatusOntvangenBerichten()
            If rbOntvangenBerichtenOK.Checked = True Then
                MessageBox.Show("De weergave werd correct aangemaakt.")
            End If
        Else
            MessageBox.Show("Er werden nog geen e-mailadressen toegevoegd.")
        End If

    End Sub

    Private Sub btnVerzondenBerichten_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVerzondenBerichten.Click
        If emailsSet() Then
            InitVerzondenBerichten()
            checkStatusVerzondenBerichten()

            If rbVerzondenBerichtenOK.Checked = True Then
                MessageBox.Show("De weergave werd correct aangemaakt.")
            End If
        Else
            MessageBox.Show("Er werden nog geen e-mailadressen toegevoegd.")
        End If
    End Sub

    Private Sub checkStatusOntvangenBerichten()
        Dim vws As Outlook.Views = SharedFunctions.GetInboxFolder(Globals.ThisAddIn.Application).Views

        Dim obView As Outlook.View = Nothing
        Dim xmlDoc As New Xml.XmlDocument

        obView = vws("Ontvangen berichten")


        If obView IsNot Nothing Then
            xmlDoc.LoadXml(obView.XML)
            'viewNode = xmlDoc.SelectSingleNode("view")
            If xmlDoc.GetElementsByTagName("filter").Count > 0 Then
                rbOntvangenBerichtenOK.Checked = True
            Else
                rbOntvangenBerichtenNOK.Checked = True
            End If
        Else
            rbOntvangenBerichtenNOK.Checked = True
        End If
    End Sub
    Private Sub checkStatusVerzondenBerichten()
        Dim vws As Outlook.Views = SharedFunctions.GetInboxFolder(Globals.ThisAddIn.Application).Views

        Dim vbView As Outlook.View = Nothing
        Dim xmlDoc As New Xml.XmlDocument

        vbView = vws("Verzonden berichten")


        If vbView IsNot Nothing Then
            xmlDoc.LoadXml(vbView.XML)
            'viewNode = xmlDoc.SelectSingleNode("view")
            If xmlDoc.GetElementsByTagName("filter").Count > 0 Then
                rbVerzondenBerichtenOK.Checked = True
            Else
                rbVerzondenBerichtenNOK.Checked = True
            End If
        Else
            rbVerzondenBerichtenNOK.Checked = True
        End If
    End Sub



    Private Sub InitSearchFolders()
        Dim folderReactionsToday As Outlook.MAPIFolder
        Dim folderReactionsThisWeek As Outlook.MAPIFolder
        Dim folderReactionsNextWeek As Outlook.MAPIFolder


        Dim sScope As String
        Dim sFolderPath As String
        Dim sFilter As String
        Dim oSearch As Outlook.Search

        Dim filterBuilder As New System.Text.StringBuilder


        sFolderPath = SharedFunctions.GetInboxFolder(Globals.ThisAddIn.Application).FolderPath
        sScope = "SCOPE ('shallow traversal of " & Chr(34) & sFolderPath & Chr(34) & "')"


        'reactionsToday
        '------------------------------------------
        'first remove if exist
        If ConfigurationHelper.ReactionsTodayEntryID IsNot Nothing AndAlso ConfigurationHelper.ReactionsTodayEntryID.Length > 0 Then
            Try
                Globals.ThisAddIn.Application.GetNamespace("mapi").GetFolderFromID(ConfigurationHelper.ReactionsTodayEntryID).Delete()
            Catch ex As Exception
                'do nothing
            End Try
            ConfigurationHelper.SetKeyvalue("ReactionsTodayEntryID", "")
        End If


        filterBuilder.Append("(")
        'mail gemarkeerd met rode vlag
        filterBuilder.Append("""http://schemas.microsoft.com/mapi/proptag/0x10950003"" = 6")

        'einddatum vandaag
        filterBuilder.Append(" AND %today(""urn:schemas:httpmail:reply-by"")% ")

        filterBuilder.Append(")")

        sFilter = filterBuilder.ToString
        oSearch = Globals.ThisAddIn.Application.AdvancedSearch(sScope, sFilter, True, "Reacties tegen vandaag")

        'set configurationValue
        folderReactionsToday = oSearch.Save("Reacties tegen vandaag")
        ConfigurationHelper.SetKeyvalue("ReactionsTodayEntryID", folderReactionsToday.EntryID)


        'reactionsThisWeek
        '------------------------------------------
        'first remove if exist

        If ConfigurationHelper.ReactionsThisWeekEntryID IsNot Nothing AndAlso ConfigurationHelper.ReactionsThisWeekEntryID.Length > 0 Then
            Try
                Globals.ThisAddIn.Application.GetNamespace("mapi").GetFolderFromID(ConfigurationHelper.ReactionsThisWeekEntryID).Delete()
            Catch ex As Exception
                'do nothing
            End Try
            ConfigurationHelper.SetKeyvalue("ReactionsThisWeekEntryID", "")
        End If

        filterBuilder = New System.Text.StringBuilder
        filterBuilder.Append("(")
        'mail gemarkeerd met rode vlag
        filterBuilder.Append("""http://schemas.microsoft.com/mapi/proptag/0x10950003"" = 6")

        'einddatum deze week
        filterBuilder.Append(" AND %thisweek(""urn:schemas:httpmail:reply-by"")% ")

        filterBuilder.Append(")")

        sFilter = filterBuilder.ToString
        oSearch = Globals.ThisAddIn.Application.AdvancedSearch(sScope, sFilter, True, "Reacties tegen deze week")

        'set configurationValue
        folderReactionsThisWeek = oSearch.Save("Reacties tegen deze week")
        ConfigurationHelper.SetKeyvalue("ReactionsThisWeekEntryID", folderReactionsThisWeek.EntryID)




        'reactionsNextWeek
        '------------------------------------------
        'first remove if exist
        If ConfigurationHelper.ReactionsNextWeekEntryID IsNot Nothing AndAlso ConfigurationHelper.ReactionsNextWeekEntryID.Length > 0 Then
            Try
                Globals.ThisAddIn.Application.GetNamespace("mapi").GetFolderFromID(ConfigurationHelper.ReactionsNextWeekEntryID).Delete()
            Catch ex As Exception
                'do nothing
            End Try
            ConfigurationHelper.SetKeyvalue("ReactionsNextWeekEntryID", "")
        End If
        filterBuilder = New System.Text.StringBuilder
        filterBuilder.Append("(")
        'mail gemarkeerd met rode vlag
        filterBuilder.Append("""http://schemas.microsoft.com/mapi/proptag/0x10950003"" = 6")

        'einddatum deze week
        filterBuilder.Append(" AND %nextweek(""urn:schemas:httpmail:reply-by"")% ")

        filterBuilder.Append(")")

        sFilter = filterBuilder.ToString
        oSearch = Globals.ThisAddIn.Application.AdvancedSearch(sScope, sFilter, True, "Reacties tegen volgende week")

        'set configurationValue
        folderReactionsNextWeek = oSearch.Save("Reacties tegen volgende week")
        ConfigurationHelper.SetKeyvalue("ReactionsNextWeekEntryID", folderReactionsNextWeek.EntryID)

        checkStatusZoekmappen()
    End Sub

    Private Sub btnZoekmappenAanmaken_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnZoekmappenAanmaken.Click
        InitSearchFolders()
    End Sub

    Private Sub checkStatusZoekmappen()
        If ConfigurationHelper.ReactionsTodayEntryID IsNot Nothing AndAlso ConfigurationHelper.ReactionsThisWeekEntryID IsNot Nothing AndAlso ConfigurationHelper.ReactionsNextWeekEntryID IsNot Nothing Then
            If ConfigurationHelper.ReactionsTodayEntryID.Length > 0 AndAlso ConfigurationHelper.ReactionsThisWeekEntryID.Length > 0 AndAlso ConfigurationHelper.ReactionsNextWeekEntryID.Length > 0 Then
                rbZoekmappenOK.Checked = True
            Else
                rbZoekmappenNOK.Checked = True
            End If
        Else
            rbZoekmappenNOK.Checked = True
        End If


    End Sub

  
End Class